/*
 * BanBu_VideoVerifyViewController
 * @description 本文件提供视频认证拍摄视频界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供视频认证拍摄视频界面的ViewController
 */
#import "BanBu_VideoVerifyViewController.h"
#import "UIViewController+Animation.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_AvatarSelectViewController.h"
#import "BanBu_VIPAlert.h"
@interface BanBu_VideoVerifyViewController ()
{
    NSTimer *timer;
    int timeLeft;
    UILabel *verifyLabel;
}
@end
//NSInteger verifyTime;
@implementation BanBu_VideoVerifyViewController

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}

-(id)initWithRegisterVerify:(BOOL)_flag andParentViewController:(BanBu_AvatarSelectViewController *)_parent
{
    self = [super init];
    if(self)
    {
        isRegisterVerify = _flag;
        parent = _parent;
    }
    return self;
}

-(void)dealloc
{
    [_curVideo release],_curVideo = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    //    [super viewDidLoad];
    timeLeft = 6;
    _curVideo = [[NSMutableDictionary alloc] initWithCapacity:0];
    _previewView = [[UIView alloc] initWithFrame:CGRectZero];
    _previewView.backgroundColor = [UIColor blackColor];
    [_previewView setFrame:CGRectMake(0, 0, 320, __MainScreen_Height+20)];
    
    // add AV layer
    _previewLayer = [[PBJVision sharedInstance] previewLayer];
    CGRect previewBounds = _previewView.layer.bounds;
    _previewLayer.bounds = CGRectMake(0, 0, 320, __MainScreen_Height+20);
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.position = CGPointMake(CGRectGetMidX(previewBounds), CGRectGetMidY(previewBounds));
    [_previewView.layer addSublayer:_previewLayer];
    [self.view addSubview:_previewView];
    
    _previewLayer.frame = CGRectMake(0, 0, 320, __MainScreen_Height+20);
    
    [[PBJVision sharedInstance] setVideoVerify:YES];
    
    
    //    timeLeft = verifyTime;
    [PBJVision sharedInstance].delegate = self;
    
    
    
    NSString *timeString = [NSString stringWithFormat:@"%@%d",NSLocalizedString(@"verifying", nil),timeLeft];
    CGFloat width = [timeString sizeWithFont:[UIFont systemFontOfSize:19] constrainedToSize:CGSizeMake(320, 50) lineBreakMode:kTextLineBreakByWordWrapping].width;
    
    verifyLabel = [[UILabel alloc] initWithFrame:CGRectMake((__MainScreen_Width-width)/2, __MainScreen_Height-100, __MainScreen_Width, 50)];
    verifyLabel.backgroundColor = [UIColor clearColor];
    verifyLabel.font = [UIFont boldSystemFontOfSize:19];
    verifyLabel.textColor = [UIColor whiteColor];
    verifyLabel.text = timeString;
    [self.view addSubview:verifyLabel];
    [verifyLabel release];
    //    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"3秒后开始录制", nil) activityAnimated:NO duration:1];
    [self performSelector:@selector(startCaption) withObject:nil afterDelay:1];
    //    UIButton * buton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //    buton.frame = CGRectMake(50, 400, 40, 30);
    //    [buton setTitle:@"录制" forState:UIControlStateNormal];
    //    [buton addTarget:self action:@selector(startCaption) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:buton];
    
	// Do any additional setup after loading the view.
}
-(void)startCaption
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimeLabel) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [self _startCapture];
    NSLog(@"%d",[[PBJVision sharedInstance] isRecording]);
}

-(void)updateTimeLabel
{
    timeLeft--;
    verifyLabel.text = [NSString stringWithFormat:@"%@%d",NSLocalizedString(@"verifying", nil),timeLeft];
    NSLog(@"%d",[PBJVision sharedInstance].isRecording);
    if(timeLeft == 0)
    {
        [self endVideoCaptureVerify];
        //        [[PBJVision sharedInstance] _destroyCamera];
        verifyLabel.text = @"";
        [timer invalidate];
        timer = nil;
    }
}


//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [[PBJVision sharedInstance] stopPreview];
//}
//
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [PBJVision sharedInstance].delegate = nil;
    [[PBJVision sharedInstance] stopPreview];
}
//-(void)playDefinitionButton
//{
//
//}
-(void)endVideoCaptureVerify
{
    [self _endCapture];
}

#pragma mark - 保存录制的视频
//保存录制的视频
- (void)vision:(PBJVision *)vision capturedVideo:(NSDictionary *)videoDict error:(NSError *)error
{
    if (error)
    {
        return;
    }
    [_curVideo removeAllObjects];
    [_curVideo addEntriesFromDictionary:videoDict];
    
    //2014年10月09日11:38:45 by yinlinlin 适配ios8
    if (IS_IOS_8)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"ifNotUploadVerifyInfo", nil) preferredStyle:UIAlertControllerStyleAlert];
        __block BanBu_VideoVerifyViewController * bself = self;
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSString *videoPath = [_curVideo  objectForKey:PBJVisionVideoPathKey];
            [AppComManager uploadVerifyData:[NSData dataWithContentsOfFile:videoPath] image:UIImageJPEGRepresentation(bself.uploadImage, 0.5) delegate:nil];
#pragma mark - 首次注册进行视频认证
            if(isRegisterVerify)
            {
                BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.logined = YES;
                [delegate setViewController:YES];
                [bself dismissViewControllerAnimated:NO];
                
                //        [parent.navigationController popToViewController:MyAppDataManager.personCon animated:YES];
            }
            else
            {
#pragma mark - 在个人空间选择视频认证
                [bself dismissViewControllerAnimated:YES];
                NSLog(@"%@ %@",MyAppDataManager.personCon,parent);
                [parent.navigationController popToViewController:MyAppDataManager.personCon animated:YES];
                //        [parent.navigationController popToViewController:[BanBu_VIPAlert shareInstance].controller animated:YES];
            }

        }];
        
        // Add the actions.
        [alert addAction:otherAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"ifNotUploadVerifyInfo", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
        [alert show];
        [alert release];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *videoPath = [_curVideo  objectForKey:PBJVisionVideoPathKey];
    [AppComManager uploadVerifyData:[NSData dataWithContentsOfFile:videoPath] image:UIImageJPEGRepresentation(self.uploadImage, 0.5) delegate:nil];
    
    if(isRegisterVerify)
    {
        BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.logined = YES;
        [delegate setViewController:YES];
        [self dismissViewControllerAnimated:NO];
        
//        [parent.navigationController popToViewController:MyAppDataManager.personCon animated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES];
        NSLog(@"%@ %@",MyAppDataManager.personCon,parent);
         [parent.navigationController popToViewController:MyAppDataManager.personCon animated:YES];
//        [parent.navigationController popToViewController:[BanBu_VIPAlert shareInstance].controller animated:YES];
    }
}
@end
